package cn.jingyuan.owl.utils.spring.context;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;


/**
 * Spring 上下文工具
 */
public class SpringContextSupport implements ApplicationContextAware {

    private static ApplicationContext context;

    private SpringContextSupport() { }

    /**
     * 根据 bean 的名称获取 bean 实例
     *
     * @param name Bean的名称
     * @param <T> Bean类对象
     *
     * @return 实例
     */
    public static <T> T getBean(String name) {
        checkApplicationContext();
        return (T) context.getBean(name);
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        checkApplicationContext();
        return context.getBean(name, requiredType);
    }

    public static <T> T getBean(Class<T> clazz) {
        checkApplicationContext();
        return context.getBean(clazz);
    }

    public static <T> Map<String, T> getBeansOfType(Class<T> clazz) {
        checkApplicationContext();
        return context.getBeansOfType(clazz);
    }

    private static void checkApplicationContext() {
        if (context == null) {
            throw new IllegalStateException("applicationContext not inject");
        }
    }

    @Override
    public final synchronized void setApplicationContext(ApplicationContext applicationContext) {
        if (null == applicationContext) {
            throw new NullPointerException("applicationContext is null");
        }
        
        context = applicationContext;
    }

}